import React from 'react';
import { Card, Table, Button, Space, Input, Form, Select, Tag, DatePicker, Tooltip } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

const { Option } = Select;
const { RangePicker } = DatePicker;

interface InterfaceLogRecord {
  id: string;
  region: string;
  platformType: 'basic' | 'management';
  platformName: string;
  interfaceName: string;
  interfacePath: string;
  method: string;
  requestParams: string;
  responseData: string;
  responseTime: number;
  status: string;
  errorMessage?: string;
  createTime: string;
}

interface PlatformTypeConfig {
  text: string;
  color: string;
}

type PlatformTypeMap = {
  [K in InterfaceLogRecord['platformType']]: PlatformTypeConfig;
};

const InterfaceLog: React.FC = () => {
  const [form] = Form.useForm();

  const handleSearch = () => {
    form.validateFields().then(values => {
      console.log('Search values:', values);
    });
  };

  const handleReset = () => {
    form.resetFields();
  };

  const handleExport = () => {
    console.log('Export logs');
  };

  const columns: ColumnsType<InterfaceLogRecord> = [
    {
      title: '日志ID',
      dataIndex: 'id',
      key: 'id',
      width: 120,
      ellipsis: true,
    },
    {
      title: '调用方平台',
      children: [
        {
          title: '地区',
          dataIndex: 'region',
          key: 'region',
          width: 100,
        },
        {
          title: '平台类型',
          dataIndex: 'platformType',
          key: 'platformType',
          width: 120,
          render: (type: InterfaceLogRecord['platformType']) => {
            const typeMap: PlatformTypeMap = {
              basic: { text: '基础支撑平台', color: 'blue' },
              management: { text: '管理平台', color: 'green' },
            };
            return <Tag color={typeMap[type].color}>{typeMap[type].text}</Tag>;
          },
        },
        {
          title: '平台名称',
          dataIndex: 'platformName',
          key: 'platformName',
          width: 150,
          ellipsis: true,
        },
      ],
    },
    {
      title: '接口信息',
      children: [
        {
          title: '接口名称',
          dataIndex: 'interfaceName',
          key: 'interfaceName',
          width: 150,
          ellipsis: true,
        },
        {
          title: '接口路径',
          dataIndex: 'interfacePath',
          key: 'interfacePath',
          width: 200,
          ellipsis: true,
        },
        {
          title: '请求方式',
          dataIndex: 'method',
          key: 'method',
          width: 100,
          render: (method: string) => {
            const colorMap: { [key: string]: string } = {
              GET: 'blue',
              POST: 'green',
              PUT: 'orange',
              DELETE: 'red',
            };
            return <Tag color={colorMap[method]}>{method}</Tag>;
          },
        },
      ],
    },
    {
      title: '请求参数',
      dataIndex: 'requestParams',
      key: 'requestParams',
      width: 200,
      ellipsis: true,
      render: (text: string) => (
        <Tooltip title={<pre>{text}</pre>} overlayStyle={{ maxWidth: 800 }}>
          <span>{text}</span>
        </Tooltip>
      ),
    },
    {
      title: '响应数据',
      dataIndex: 'responseData',
      key: 'responseData',
      width: 200,
      ellipsis: true,
      render: (text: string) => (
        <Tooltip title={<pre>{text}</pre>} overlayStyle={{ maxWidth: 800 }}>
          <span>{text}</span>
        </Tooltip>
      ),
    },
    {
      title: '响应时间(ms)',
      dataIndex: 'responseTime',
      key: 'responseTime',
      width: 120,
      render: (time: number) => {
        let color = 'success';
        if (time > 1000) {
          color = 'warning';
        }
        if (time > 3000) {
          color = 'error';
        }
        return <Tag color={color}>{time}</Tag>;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string, record: InterfaceLogRecord) => {
        const color = status === 'success' ? 'success' : 'error';
        const text = status === 'success' ? '成功' : '失败';
        return (
          <Tooltip title={record.errorMessage}>
            <Tag color={color}>{text}</Tag>
          </Tooltip>
        );
      },
    },
    {
      title: '调用时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 160,
    },
  ];

  const mockData: InterfaceLogRecord[] = [
    {
      id: 'IF-001',
      region: '北京',
      platformType: 'basic',
      platformName: '北京市基础支撑平台',
      interfaceName: '获取用户信息',
      interfacePath: '/api/v1/users/{id}',
      method: 'GET',
      requestParams: JSON.stringify({ id: '12345' }, null, 2),
      responseData: JSON.stringify({ id: '12345', name: '张三', age: 30 }, null, 2),
      responseTime: 200,
      status: 'success',
      createTime: '2024-01-20 10:30:00',
    },
    {
      id: 'IF-002',
      region: '上海',
      platformType: 'management',
      platformName: '上海市统一管理平台',
      interfaceName: '创建订单',
      interfacePath: '/api/v1/orders',
      method: 'POST',
      requestParams: JSON.stringify({ productId: 'P001', quantity: 2 }, null, 2),
      responseData: JSON.stringify({ orderId: 'O001', status: 'created' }, null, 2),
      responseTime: 500,
      status: 'success',
      createTime: '2024-01-20 11:15:00',
    },
    {
      id: 'IF-003',
      region: '广州',
      platformType: 'basic',
      platformName: '广州市基础支撑平台',
      interfaceName: '更新用户信息',
      interfacePath: '/api/v1/users/{id}',
      method: 'PUT',
      requestParams: JSON.stringify({ id: '12345', name: '李四' }, null, 2),
      responseData: JSON.stringify({ error: 'User not found' }, null, 2),
      responseTime: 3500,
      status: 'error',
      errorMessage: '用户不存在',
      createTime: '2024-01-20 13:45:00',
    },
    {
      id: 'IF-004',
      region: '深圳',
      platformType: 'management',
      platformName: '深圳市统一管理平台',
      interfaceName: '查询产品列表',
      interfacePath: '/api/v1/products',
      method: 'GET',
      requestParams: JSON.stringify({ category: 'electronics', page: 1 }, null, 2),
      responseData: JSON.stringify({ total: 100, items: [] }, null, 2),
      responseTime: 1500,
      status: 'success',
      createTime: '2024-01-20 14:00:00',
    },
  ];

  return (
      <Card bordered={false}>
        <Form
          form={form}
          layout="inline"
          style={{ marginBottom: '24px' }}
          onFinish={handleSearch}
        >
          <Form.Item name="timeRange" label="调用时间">
            <RangePicker showTime />
          </Form.Item>
          <Form.Item name="region" label="地区">
            <Select placeholder="请选择地区" style={{ width: 120 }}>
              <Option value="北京">北京</Option>
              <Option value="上海">上海</Option>
              <Option value="广州">广州</Option>
              <Option value="深圳">深圳</Option>
            </Select>
          </Form.Item>
          <Form.Item name="platformType" label="平台类型">
            <Select placeholder="请选择平台类型" style={{ width: 150 }}>
              <Option value="basic">基础支撑平台</Option>
              <Option value="management">管理平台</Option>
            </Select>
          </Form.Item>
          <Form.Item name="platformName" label="平台名称">
            <Input placeholder="请输入平台名称" />
          </Form.Item>
          <Form.Item name="interfaceName" label="接口名称">
            <Input placeholder="请输入接口名称" />
          </Form.Item>
          <Form.Item name="method" label="请求方式">
            <Select placeholder="请选择请求方式" style={{ width: 120 }}>
              <Option value="GET">GET</Option>
              <Option value="POST">POST</Option>
              <Option value="PUT">PUT</Option>
              <Option value="DELETE">DELETE</Option>
            </Select>
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select placeholder="请选择状态" style={{ width: 120 }}>
              <Option value="success">成功</Option>
              <Option value="error">失败</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button onClick={handleReset}>重置</Button>
            </Space>
          </Form.Item>
        </Form>

        <div style={{ marginBottom: '16px', display: 'flex', justifyContent: 'flex-end' }}>
          <Button icon={<DownloadOutlined />} onClick={handleExport}>
            导出日志
          </Button>
        </div>

        <Table<InterfaceLogRecord>
          columns={columns}
          dataSource={mockData}
          rowKey="id"
          scroll={{ x: 1800 }}
          pagination={{
            total: mockData.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
        />
      </Card>
  );
};

export default InterfaceLog; 